#!python3
# 使用 SAX 解析 xml

import xml
from xml.sax import parse
from xml.sax.handler import ContentHandler


class MovieHandler(ContentHandler):
    """
    定义了一个继承 ContentHandler 的类,并重写了下面的方法
    """

    def __init__(self):

        # 用于记录当前解析的是哪个标签
        self.CurrentData = ""

        # 以下属性与样例xml对应
        self.type = ""
        self.format = ""
        self.year = ""
        self.rating = ""
        self.stars = ""
        self.description = ""

    def startElement(self, tag, attributes):
        """
        元素开始调用
        :param tag: 标签的名字
        :param attributes:标签的属性值字典
        :return:
        """
        self.CurrentData = tag
        if tag == "movie":
            print("***************"*4)
            title = attributes["title"]  # 获取标签的title属性值
            print("Title:", title)

    def endElement(self, tag):
        """
        元素结束调用
        :param tag:
        :return:
        """
        if self.CurrentData == "type":
            print("Type:", self.type)
        elif self.CurrentData == "format":
            print("Format:", self.format)
        elif self.CurrentData == "year":
            print("Year:", self.year)
        elif self.CurrentData == "rating":
            print("Rating:", self.rating)
        elif self.CurrentData == "stars":
            print("Stars:", self.stars)
        elif self.CurrentData == "description":
            print("Description:", self.description)
        self.CurrentData = ""

    def characters(self, content):
        """
        读取字符时调用
        :param content:
        :return:
        """
        if self.CurrentData == "type":
            self.type = content
        elif self.CurrentData == "format":
            self.format = content
        elif self.CurrentData == "year":
            self.year = content
        elif self.CurrentData == "rating":
            self.rating = content
        elif self.CurrentData == "stars":
            self.stars = content
        elif self.CurrentData == "description":
            self.description = content


if __name__ == "__main__":

    # 创建一个 XMLReader
    parser = xml.sax.make_parser()

    # 关闭命名空间
    parser.setFeature(xml.sax.handler.feature_namespaces, 0)

    # 重写 ContextHandler
    Handler = MovieHandler()
    parser.setContentHandler(Handler)

    parser.parse("template.xml")
